package com.example.administrator.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private String[]  titles ={"java","php","python","html","css"};
    private String[]  content ={""};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initEvent();
    }
    private void initView(){
        listView = findViewById(R.id.listview);
      listView.setAdapter(new MyBaseAdapter());

    }
    private void initData(){

    }
    private void initEvent(){
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(MainActivity.this,"我点击了条目（下标还是，当前位置）"+i,Toast.LENGTH_SHORT).show();
        }
    });
    }
    class ViewHolder{
        TextView title;
    }

    class MyBaseAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public  Object getItem(int i) {
            return titles[i];
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            ViewHolder viewHolder = null;
            if(viewHolder==null) { //当视图不存在的时候我们需要创建
                //加载item布局
                //初始化viewholder
                view = View.inflate(MainActivity.this,R.layout.item_layout,null);
                viewHolder = new ViewHolder();
                //通过viewholder初始化控件
                viewHolder.title =view.findViewById(R.id.item_title_tv);
                //在ListView条目布局里缓存控件
                view.setTag(viewHolder);


            }else{
                //如果在缓存中存在当前视图，则至鸡肉获取当前视图
                viewHolder = (ViewHolder) view.getTag();
            }
            viewHolder.title.setText(titles[i]);

            return view;

        }
    }
}
